from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from ..models.user import User
from ..forms import UserForm
from .. import db

user_bp = Blueprint('user', __name__)

@user_bp.route('/list')
@login_required
def list():
    # 只有管理员可以查看用户列表
    if not current_user.is_admin:
        flash('权限不足', 'danger')
        return redirect(url_for('main.index'))
    
    users = User.query.all()
    return render_template('user/list.html', users=users)

@user_bp.route('/new', methods=['GET', 'POST'])
@login_required
def create():
    # 只有管理员可以创建用户
    if not current_user.is_admin:
        flash('权限不足', 'danger')
        return redirect(url_for('main.index'))
    
    form = UserForm()
    if form.validate_on_submit():
        user = User(
            username=form.username.data,
            email=form.email.data,
            is_admin=form.is_admin.data
        )
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('用户创建成功', 'success')
        return redirect(url_for('user.list'))
    return render_template('user/form.html', form=form, title='新增用户')

@user_bp.route('/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def edit(id):
    # 只有管理员可以编辑用户
    if not current_user.is_admin:
        flash('权限不足', 'danger')
        return redirect(url_for('main.index'))
    
    user = User.query.get_or_404(id)
    form = UserForm(obj=user)
    if form.validate_on_submit():
        user.username = form.username.data
        user.email = form.email.data
        user.is_admin = form.is_admin.data
        if form.password.data:
            user.set_password(form.password.data)
        db.session.commit()
        flash('用户信息更新成功', 'success')
        return redirect(url_for('user.list'))
    return render_template('user/form.html', form=form, title='编辑用户')

@user_bp.route('/<int:id>/delete', methods=['POST'])
@login_required
def delete(id):
    # 只有管理员可以删除用户
    if not current_user.is_admin:
        flash('权限不足', 'danger')
        return redirect(url_for('main.index'))
    
    user = User.query.get_or_404(id)
    if user == current_user:
        flash('不能删除当前登录用户', 'danger')
        return redirect(url_for('user.list'))
    
    db.session.delete(user)
    db.session.commit()
    flash('用户已删除', 'success')
    return redirect(url_for('user.list'))

@user_bp.route('/test')
def test():
    return 'User blueprint test route' 